package com.changjiang.myproductsale.myproduct.servlet;

import com.changjiang.myproductsale.myproduct.dao.impl.ProductImpl;
import com.changjiang.myproductsale.myproduct.entity.Product;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ServletList", value = "/list")
public class ServletList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //A接受请求  //list?cateId=3&pagesize=5&pagenum=1
            int cateId = Integer.parseInt(request.getParameter("category_id"));
            int pageNum = Integer.parseInt(request.getParameter("pagenum"));
            int pageSize = Integer.parseInt(request.getParameter("pagesize"));
            //B处理 调用后端代码
            ProductImpl productDao = new ProductImpl();
            //分页查询商品信息
            List<Product> plist = productDao.getProductByCatePage(cateId, pageSize, pageNum);
            //查询商品的总数量
            int totalNum = productDao.getProductCountByCate(cateId);
            System.out.println("数据：" + plist.size());
            System.out.println("总数：" + totalNum);
            //计算总页数
            int totalPage=0;
            if(totalNum%pageSize==0)
                totalPage=totalNum/pageSize;
            else
                totalPage=totalNum/pageSize+1;
            //C去不同的页面
            request.setAttribute("plist", plist);
            request.setAttribute("total", totalPage);
            request.setAttribute("cateId", cateId);
            request.getRequestDispatcher("/productlist.jsp").forward(request, response);
        }catch (Exception ex){
            ex.printStackTrace();
            response.sendRedirect("500.html");
        }
    }
}
